<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/9/25
 * Time: 23:08
 */

namespace App\Repository;


use App\Exceptions\ModelDuplicateException;
use App\Model\Admin;
use App\Model\Role;

class AdminRepository
{
    protected $admin;

    public function __construct(Admin $admin)
    {
        $this->admin = $admin;
    }

    public function all()
    {
        return Admin::all();
    }

    public function allWithUser()
    {
        return Admin::with('user')->get();
    }

    /**
     * 增加管理员
     *
     * @param $number
     * @param $password
     * @return bool|static
     * @throws ModelDuplicateException
     */
    public function add($number, $password)
    {
        if($admin = $this->findByNumber($number)){
            throw new ModelDuplicateException('用户 ' . $number);
        }

        return Admin::create(['number' => $number, 'password' => $password]);
    }

    /**
     * 通过学号找管理员
     *
     * @param $number
     * @return array|\Illuminate\Database\Eloquent\Model|null|\stdClass|static
     */
    public function findByNumber($number)
    {
        return Admin::whereNumber($number)->first();
    }

    public function delete($id)
    {
        return Admin::destroy($id);
    }

    public function getAdminsByName($roleName)
    {
        $role = Role::where('name', $roleName)->first();
        return $role ? $role->users()->with('user')->get() : false;
    }
}